// pages/app/user/signUp/signUp.js
const app = getApp();
var host = app.globalData.host;
var utils = app.globalData.utils;
var cryptoJS = app.globalData.cryptoJS;
var self = null;

Page({
  data: {
    themeColor: '',
    themeColor2: '',
    themeColor3: '',
    defaultColor: '',
    borderColor: '',

    editMode: false,
    id: '',
    account: '',
    password: '',
    name: '',
    lastName: '',
    firstName: '',
    englishName: '',
    sex: '',
    province: '',
    city: '',
    region: '',
    companyId: '',
    country: '',
    department: '',
    startDate: '',
    postgradSchool: '',
    postgradMajor: '',
    undergradSchool: '',
    undergradMajor: '',
    hobby: '',
    card: '',

    postgradSchoolName: '',
    undergradSchoolName: '',

    sexArray: ["男", "女"],
    companyArray: [],
    companyIndex: '',
    companyName: '',
    // countryArray: ["港澳台", "英国", "澳大利亚", "美国", "加拿大", "爱尔兰", "新西兰", "其他"],
    countryArray: [{
      country: "港澳台",
      selected: 0
    }, {
      country: "英国",
      selected: 0
    }, {
      country: "澳大利亚",
      selected: 0
    }, {
      country: "美国",
      selected: 0
    }, {
      country: "加拿大",
      selected: 0
    }, {
      country: "爱尔兰",
      selected: 0
    }, {
      country: "新西兰",
      selected: 0
    }, {
      country: "其他",
      selected: 0
    }],
    countryIndex: '',
    departmentArray: ["咨询顾问", "文案申请", "外联及其他", "公司管理"],
    departmentIndex: '',
    majorArray: ["数学和自然科学 Mathematics and Science", "医学 Medical Sciences", "工程 Engineering", "人文艺术 Humanities and Arts", "社会科学 Social Sciences", "商业与经济 Business and Economics"],
    majorIndex1: '',
    majorIndex2: '',
    hobbyArray: [],
    hobbyIndex: '',
    location: []
  },
  onLoad: function(options) {
    self = this;
    self.getStyle();
    self.init(options.editMode);
    if (!self.data.editMode && options.account) {
      self.setData({
        account: options.account
      })
    }
  },
  getStyle() {
    self.setData({
      themeColor: app.globalData.themeColor,
      themeColor2: app.globalData.themeColor2,
      themeColor3: app.globalData.themeColor3,
      defaultColor: app.globalData.defaultColor,
      borderColor: app.globalData.borderColor
    })
  },
  init(editMode) {
    // self.setData({
    //   majorArray: app.globalData.majors
    // })
    // if (wx.getStorageSync("user")) {
    if (editMode == 1) {
      var user = wx.getStorageSync("user");
      self.setData({
        editMode: true,
        id: user.id,
        account: user.account,
        password: user.password,
        name: user.name,
        lastName: user.lastName == null ? '' : user.lastName,
        firstName: user.firstName == null ? '' : user.firstName,
        englishName: user.englishName == null ? '' : user.englishName,
        sex: user.sex == null ? '' : user.sex,
        // location: user.province + "," + user.city,
        province: user.province == null ? '' : user.province,
        city: user.city == null ? '' : user.city,
        region: user.region == null ? '' : user.region,
        companyId: user.companyId == null ? '' : user.companyId,
        country: user.country == null ? '' : user.country,
        department: user.department == null ? '' : user.department,
        startDate: user.startDate == null ? '' : user.startDate,
        postgradSchool: user.postgradSchool == null ? '' : user.postgradSchool,
        postgradMajor: user.postgradMajor == null ? '' : user.postgradMajor,
        undergradSchool: user.undergradSchool == null ? '' : user.undergradSchool,
        undergradMajor: user.undergradMajor == null ? '' : user.undergradMajor,
        hobby: user.hobby == null ? '' : user.hobby,
        card: user.card == null ? '' : user.card,
        wechatPortrait: user.wechatPortrait == null ? '' : user.wechatPortrait,
        wechatNickname: user.wechatNickname == null ? '' : user.wechatNickname
      })
      wx.setNavigationBarTitle({
        title: '编辑'
      })
    } else {
      self.setData({
        editMode: false
      })
      wx.setNavigationBarTitle({
        title: '注册'
      })
      wx.getUserInfo({
        success: function (res) {
          var userInfo = res.userInfo
          var nickName = userInfo.nickName
          var avatarUrl = userInfo.avatarUrl
          var gender = userInfo.gender //性别 0：未知、1：男、2：女
          var province = userInfo.province
          var city = userInfo.city
          var country = userInfo.country

          var sex = gender == 1 ? 0 : (gender == 2 ? 1 : '');
          self.setData({
            wechatNickname: nickName,
            wechatPortrait: avatarUrl,
            sex: sex
          })
        }
      })
    }

    // 公司列表
    // var url = host + '/lx/mini/user/company';
    // var params = {};
    // var success = function(res) {
    //   var list = res.info;
    //   self.setData({
    //     companyArray: list
    //   })

    //   if (self.data.companyId) {
    //     for (var i = 0; i < self.data.companyArray.length; i++) {
    //       if (self.data.companyId == self.data.companyArray[i].id) {
    //         self.setData({
    //           companyIndex: i
    //         })
    //       }
    //     }
    //   }
    // }
    // var fail = function() {};
    // var complete = function() {};
    // utils.request(url, params, success, fail, complete);

    if (self.data.companyId) {
      wx.request({
        url: host + '/lx/mini/user/companyInfo',
        data: {
          id: self.data.companyId
        },
        success: function(res) {
          self.setData({
            companyName: res.data.info.name
          })
        }
      })
    }

    if (self.data.country) {
      var list = self.data.country.split("、");
      var countryArray = self.data.countryArray;
      for (var i = 0; i < list.length; i ++) {
        for (var j = 0; j < countryArray.length; j ++) {
          if (list[i] === countryArray[j].country) {
            countryArray[j].selected = 1;
          }
        }
      }
      self.setData({
        countryArray: countryArray
      })
    }

    if (self.data.postgradSchool) {
      wx.request({
        url: host + '/lx/mini/user/schoolInfo',
        data: {
          id: self.data.postgradSchool
        },
        success: function(res) {
          self.setData({
            postgradSchoolName: res.data.info.certificateName
          })
        }
      })
    }

    if (self.data.undergradSchool) {
      wx.request({
        url: host + '/lx/mini/user/schoolInfo',
        data: {
          id: self.data.undergradSchool
        },
        success: function(res) {
          self.setData({
            undergradSchoolName: res.data.info.certificateName
          })
        }
      })
    }
  },
  onAccountChange(e) {
    this.setData({
      account: e.detail.value
    })
  },
  onPasswordChange(e) {
    this.setData({
      password: e.detail.value
    })
  },
  onNameChange(e) {
    this.setData({
      name: e.detail.value
    })
  },
  onLastNameChange(e) {
    this.setData({
      lastName: e.detail.value
    })
  },
  onFirstNameChange(e) {
    this.setData({
      firstName: e.detail.value
    })
  },
  onEnglishNameChange(e) {
    this.setData({
      englishName: e.detail.value
    })
  },
  onSexChange(e) {
    this.setData({
      sex: e.detail.value
    })
  },
  onProvinceChange(e) {
    this.setData({
      province: e.detail.value
    })
  },
  onCityChange(e) {
    this.setData({
      city: e.detail.value
    })
  },
  onRegionChange(e) {
    this.setData({
      region: e.detail.value
    })
  },
  onLocationChange(e) {
    this.setData({
      location: e.detail.value,
      province: e.detail.value[0],
      city: e.detail.value[1],
      region: e.detail.value[2]
    })
  },
  onCompanyChange(e) {
    // if (e.detail.value == 0) {
    //   this.setData({
    //     companyIndex: e.detail.value,
    //     companyId: ''
    //   })
    // } else {
    this.setData({
      companyIndex: e.detail.value,
      companyId: self.data.companyArray[e.detail.value].id
    })
    // }
  },
  onCountryChange(e) {
    // if (e.detail.value == 0) {
    //   this.setData({
    //     countryIndex: e.detail.value,
    //     country: ''
    //   })
    // } else {
    this.setData({
      countryIndex: e.detail.value,
      country: self.data.countryArray[e.detail.value]
    })
    // }
  },
  selectCountry(e) {
    var index = Number(e.currentTarget.dataset.index);
    var array = self.data.countryArray;
    if (array[index].selected === 1) {
      array[index].selected = 0;
    } else {
      array[index].selected = 1;
    }
    self.setData({
      countryArray: array
    })
  },
  onDepartmentChange(e) {
    this.setData({
      departmentIndex: e.detail.value,
      department: self.data.departmentArray[e.detail.value]
    })
  },
  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
  },
  onPostgradSchoolChange(e) {
    this.setData({
      postgradSchool: e.detail.value
    })
  },
  onPostgradMajorChange(e) {
    this.setData({
      majorIndex1: e.detail.value,
      postgradMajor: self.data.majorArray[e.detail.value]
    })
  },
  onUndergradSchoolChange(e) {
    this.setData({
      undergradSchool: e.detail.value
    })
  },
  onUndergradMajorChange(e) {
    this.setData({
      majorIndex2: e.detail.value,
      undergradMajor: self.data.majorArray[e.detail.value]
    })
  },
  goSelectCompany(e) {
    wx.navigateTo({
      url: '/pages/app/user/selectCompany/selectCompany'
    })
  },
  goSelectSchool(e) {
    var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/app/user/selectSchool/selectSchool?type=' + type
    })
  },
  onHobbyChange(e) {
    // this.setData({
    //   hobbyIndex: e.detail.value,
    //   hobby: self.data.hobbyArray[e.detail.value]
    // })
    this.setData({
      hobby: e.detail.value
    })
  },
  uploadImage(e) {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempFiles = res.tempFiles;
        wx.showLoading({
          title: '上传中…',
          mask: true
        })
        wx.uploadFile({
          // url: host + '/lx/mini/api/upload',
          url: host + '/lx/admin/qn/upload',
          filePath: tempFiles[0].path,
          name: 'file',
          success: function(res) {
            var data = JSON.parse(res.data);
            self.setData({
              // card: data.info
              card: 'http://' + data.info
            })
          },
          complete: function() {
            wx.hideLoading();
          }
        })
      }
    })
  },
  submit(e) {
    var formId = e.detail.formId;
    var country = '';
    for (var i = 0; i < self.data.countryArray.length; i ++) {
      if (self.data.countryArray[i].selected === 1) {
        country += self.data.countryArray[i].country + '、';
      }
    }
    if (country) {
      country = country.substr(0, country.length - 1);
    }
    
    if (self.data.account === '') {
      wx.showToast({
        title: '请输入手机 / 邮箱',
        icon: 'none'
      })
      return;
    }
    if (!self.data.password) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      })
      return;
    }
    if (!self.data.name) {
      wx.showToast({
        title: '请输入中文名',
        icon: 'none'
      })
      return;
    }
    if (!self.data.lastName) {
      wx.showToast({
        title: '请输入姓（拼音）',
        icon: 'none'
      })
      return;
    }
    if (!self.data.firstName) {
      wx.showToast({
        title: '请输入名（拼音）',
        icon: 'none'
      })
      return;
    }
    if (!self.data.englishName) {
      wx.showToast({
        title: '请输入英文名',
        icon: 'none'
      })
      return;
    }
    if (self.data.sex === '') {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return;
    }
    if (!self.data.province || self.data.province == "请选择") {
      wx.showToast({
        title: '请选择省份',
        icon: 'none'
      })
      return;
    }
    if (!self.data.city || self.data.city == "请选择") {
      wx.showToast({
        title: '请选择市县',
        icon: 'none'
      })
      return;
    }
    if (!self.data.companyId) {
      wx.showToast({
        title: '请选择公司',
        icon: 'none'
      })
      return;
    }
    if (!country) {
      wx.showToast({
        title: '请选择擅长国家',
        icon: 'none'
      })
      return;
    }
    if (!self.data.department) {
      wx.showToast({
        title: '请选择职能类别',
        icon: 'none'
      })
      return;
    }
    if (!self.data.card) {
      wx.showToast({
        title: '请上传工作名片',
        icon: 'none'
      })
      return;
    }
    var url = host + (self.data.editMode ? '/lx/mini/user/submit' : '/lx/mini/user/register');
    var key = cryptoJS.enc.Utf8.parse(app.globalData.aesKey);
    var iv = cryptoJS.enc.Utf8.parse('RandomInitVector');
    var aesText = cryptoJS.AES.encrypt(self.data.password, key, {
      iv: iv,
      mode: cryptoJS.mode.CBC,
      padding: cryptoJS.pad.Pkcs7
    }).toString();

    var params = {
      id: self.data.id,
      account: self.data.account,
      password: aesText,
      // password: self.data.password,
      name: self.data.name,
      lastName: self.data.lastName,
      firstName: self.data.firstName,
      englishName: self.data.englishName,
      sex: self.data.sex,
      // location: self.data.province + "," + self.data.city,
      province: self.data.province,
      city: self.data.city,
      region: self.data.region == "请选择" ? "" : self.data.region,
      companyId: self.data.companyId,
      country: country,
      department: self.data.department,
      startDate: self.data.startDate,
      postgradSchool: self.data.postgradSchool,
      postgradMajor: self.data.postgradMajor,
      undergradSchool: self.data.undergradSchool,
      undergradMajor: self.data.undergradMajor,
      hobby: self.data.hobby,
      card: self.data.card,
      openId: app.globalData.openId,
      wechatPortrait: self.data.wechatPortrait,
      wechatNickname: self.data.wechatNickname,
      formId: formId
    };
    var success = function(res) {
      var user = res.info;
      app.globalData.userInfo = user;
      app.globalData.openId = user.openId;
      wx.setStorageSync("user", user);
      wx.setStorageSync("openId", user.openId);
      wx.showModal({
        title: self.data.editMode ? '编辑' : '注册',
        content: self.data.editMode ? '修改成功' : '注册成功',
        showCancel: false,
        success: res => {
          wx.reLaunch({
            url: '/pages/app/user/index/index'
          })
          // wx.switchTab({
          //   url: '/pages/app/user/index/index'
          // })
        }
      })
    }
    var fail = function() {};
    var complete = function() {};
    utils.request(url, params, success, fail, complete);
  }
})